Vaadin 提供的眾多 Components,除了前面範例實作過的 Form Inputs 外,常用到的還有Dialog。先前所寫的範例無論新增或修改。都是跳頁顯示,實務上顯示或修新增/修改資料時,不太會這麼使用,大都使用彈出視窗。
前例的學生資料,如果要使用彈出視窗修改該怎麼做?
請開新檔 StudentEditDialog.kt
,下列程式多半和StudentEditorComponent.kt
相同。
package com.example.vok
import com.github.mvysny.karibudsl.v10.*
import com.vaadin.flow.component.dialog.Dialog
class StudentEditDialog: Dialog() {
private val binder = beanValidationBinder<Student>()
var student: Student? = null
set(value) {
field = value
value?.let { binder.readBean(value) }
}
var studentId : Long? = null
set(value){
field = value
student = Student.getById(studentId!!)
}
init {
verticalLayout {
isMargin = false
textField("姓名 : "){
bind(binder).bind(Student::name)
}
comboBox<Gender>("性別 : "){
setItems(*Gender.values())
bind(binder).bind(Student::gender)
}
datePicker("生日 : "){
bind(binder).bind(Student::birthday)
}
horizontalLayout {
numberField("身高"){
bind(binder).bind(Student::height)
}
numberField("體重"){
bind(binder).bind(com.example.vok.Student::weight)
}
}
horizontalLayout {
button("儲存"){
onLeftClick {
val student = student!!
if (binder.validate().isOk && binder.writeBeanIfValid(student)){
student.save()
this@StudentEditDialog.close()
}
}
}
button("取消") {
onLeftClick {
this@StudentEditDialog.close()
}
}
}
}
}
}
請打開AllStudentsView.kt
,修改編輯
addButtonColumn(VaadinIcon.EDIT, "edit") {
dialog = StudentEditDialog().apply {
this.studentId = it.id
isCloseOnEsc = false
isCloseOnOutsideClick = false
open()
}
}